/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This file is part of retabel.
 *
 * Copyright (c) 2011 by individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution
 * for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.retabel.persistence.dao.document;

import org.retabel.persistence.dao.AbstractEntityDaoBean;
import org.retabel.persistence.entity.document.DocumentConfiguration;
import org.retabel.persistence.entity.document.DocumentConfigurationTypeEnum;
import org.retabel.persistence.entity.document.SectionConfiguration;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * Class description.
 * <p/>
 * <h3>Extra-Info</h3>
 * Created: 15:38 12.08.11
 *
 * @author Burt Parkers
 * @version 1.0
 */
@Stateless
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public class DocumentConfigurationDaoBean extends AbstractEntityDaoBean<DocumentConfiguration>
    implements DocumentConfigurationDao {

    /** The EntityManager. */
    @PersistenceContext(unitName = "retabel-persistence")
    private EntityManager entityManager;

    public DocumentConfigurationDaoBean() {
        super(DocumentConfiguration.class);
    }

    @Override
    protected EntityManager getEntityManager() {
        return entityManager;
    }

    @Override
    public DocumentConfiguration findByNameVersionAndType(String name, String version, DocumentConfigurationTypeEnum configurationType) {
        try {
            Query query = entityManager.createNamedQuery("DocumentConfiguration.findByNameVersionAndType");
            query.setParameter(1, name);
            query.setParameter(2, version);
            query.setParameter(3, configurationType);
            return (DocumentConfiguration) query.getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    @Override
    public DocumentConfiguration[] findAllByTypeSorted(int from, int maxResults, DocumentConfigurationTypeEnum configurationType) {
        Query query = entityManager.createNamedQuery("DocumentConfiguration.findAllByType");
        query.setParameter(1, configurationType);
        query.setFirstResult(from);
        query.setMaxResults(maxResults);

        @SuppressWarnings({"unchecked"})
        List<DocumentConfiguration> results = (List<DocumentConfiguration>) query.getResultList();

        return results.toArray(new DocumentConfiguration[results.size()]);
    }

    @Override
    public int count(DocumentConfigurationTypeEnum configurationType) {
        Query query = entityManager.createNamedQuery("DocumentConfiguration.countDocumentConfigurationsByType");
        query.setParameter(1, configurationType);

        return ((Long) query.getSingleResult()).intValue();
    }

    /**
     * removes the entity, including all temporary sections
     *
     * @param documentConfiguration the documentConfiguration to remove.
     */
    @Override
    public void remove(DocumentConfiguration documentConfiguration) {
        if (!entityManager.contains(documentConfiguration)) {
            // attach document configuration
            documentConfiguration = entityManager.merge(documentConfiguration);
        }

        // delete all temporary section configurations
        for (SectionConfiguration sectionConfiguration : documentConfiguration.getSectionConfigurations())
        {
            switch (sectionConfiguration.getConfigurationType())
            {
                case TEMPORARY: {
                    // delete the temporary section
                    entityManager.remove(sectionConfiguration);

                    break;
                }
            }
        }

        // delete all section configurations references
        documentConfiguration.getSectionConfigurations().clear();

        entityManager.remove(documentConfiguration);
    }
}
